﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class main_uc_sea_transport_app : DAO.ESWebUserControl
{
    string referrer_addr = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeUI();
        LoadDeparture();
        LoadSeaPort();
        LoadVesselTypes(this.LangId);
        LoadSpecialCondTypes(this.LangId);
        setAttributes();
        LoadRoutes(this.LangId);
        LoadLevelOfImportanceTypes(this.LangId);
        LoadPlacementTypes(this.LangId);
        if (Request.QueryString["id"] != null)
        {
            long appid = 0;
            Int64.TryParse(Request.QueryString["id"].ToString(), out appid);
            LoadTecnicalInfo(appid);

            //Edit Application
            if (Request.Cookies["texchange"] != null && Request.Cookies["texchange"]["logged"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["logged"]) == "true")
            {
                if (Request.Cookies["texchange"]["cid"] != null /*&& DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["cid"].ToString()) == dr["company_id"].ToString()*/)
                {
                    if (Request.UrlReferrer != null)
                    {
                        referrer_addr = Request.UrlReferrer.ToString();
                        if (referrer_addr != null && referrer_addr != "")
                        {
                            if (referrer_addr.ToLower().IndexOf("myapplications.aspx") != -1)
                            {
                                ShowHideFields();
                            }
                        }
                    }
                }
            }
            //If user is admin
            if (Request.Cookies["texchange"]["type"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"].ToString()) == "admin")
            {

                ShowHideFields();
            }
        }
    }

    private void ShowHideFields()
    {
        ddlLevelOfImportnce.Visible = true;
        ddlPlacementTypes.Visible = true;
        ddlDeparture.Visible = true;
        ddlVeselTypes.Visible = true;
        tbVesselBuiltDate.Visible = true;
        tbPortOfRegister.Visible = true;
        ddlFlag.Visible = true;
        tbClass.Visible = true;
        tbTimeOfDuration.Visible = true;
        ddl_time_period.Visible = false;
        tbPrice.Visible = true;
        ddlPrice.Visible = false;
        ddlSpecualConditionTypes.Visible = true;
        tbOtherInformattions.Visible = true;
        btn_UpdateTechicalInfo45.Visible = true;
        ddlRute.Visible = true;

        lblLevelOfImportance.Visible = false;
        lblPlacementType.Visible = false;
        lblDeparture.Visible = false;
        lblVeselTypes.Visible = false;
        lblVesselBuiltDate.Visible = false;
        lblPortOfRegister.Visible = false;
        lblFlag.Visible = false;
        lblClass.Visible = false;
        lblTimeOfDuration.Visible = false;
        lblRute.Visible = false;
        lblSpecualConditionTypes.Visible = false;
        lblOtherInfo.Visible = false;
        lblPrice.Visible = false;
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
    }

    public void LoadTecnicalInfo(long appid)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_GetTechnicalInfo", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add("@app_id", DbType.Int64).Value = appid;
                cmd.Parameters.Add("@type_transport_id", DbType.Int64).Value = 165;
                cmd.Parameters.Add("@type_offer_id", DbType.Int64).Value = 70;
                SqlDataReader dr = cmd.ExecuteReader();
                tb_application_id.Value = appid.ToString();

                while (dr.Read())
                {
                    tb_SeaPort_app_id.Value = dr["id"].ToString();
                    long country_id;
                    lblDeparture.Text = "N/A";
                    if (long.TryParse(dr["country_id"].ToString(), out country_id))
                    {
                        lblDeparture.Text = LoadCountryById(country_id, false);
                        if (ddlDeparture.Items.FindByValue(dr["country_id"].ToString()) != null)
                        {
                            ddlDeparture.Items.FindByValue(dr["country_id"].ToString()).Selected = true;
                        }
                    }

                    long level_importance_id;
                    lblLevelOfImportance.Text = "N/A";
                    if (long.TryParse(dr["level_importance_id"].ToString(), out level_importance_id))
                    {
                        lblLevelOfImportance.Text = LoadUniversalType(level_importance_id);
                        if (ddlLevelOfImportnce.Items.FindByValue(dr["level_importance_id"].ToString()) != null)
                        {
                            ddlLevelOfImportnce.Items.FindByValue(dr["level_importance_id"].ToString()).Selected = true;
                        }
                    }

                    long placement_type_id;
                    lblPlacementType.Text = "N/A";
                    if (long.TryParse(dr["placement_type_id"].ToString(), out placement_type_id))
                    {
                        lblPlacementType.Text = LoadUniversalType(placement_type_id);
                        if (ddlPlacementTypes.Items.FindByValue(dr["placement_type_id"].ToString()) != null)
                        {
                            ddlPlacementTypes.Items.FindByValue(dr["placement_type_id"].ToString()).Selected = true;
                        }
                    }

                    long universal_type_id;
                    lblVeselTypes.Text = "N/A";
                    if (long.TryParse(dr["universal_type_id"].ToString(), out universal_type_id))
                    {
                        lblVeselTypes.Text = LoadUniversalType(universal_type_id);
                        if (ddlVeselTypes.Items.FindByValue(dr["universal_type_id"].ToString()) != null)
                        {
                            ddlVeselTypes.Items.FindByValue(dr["universal_type_id"].ToString()).Selected = true;
                        }
                    }

                    lblPortOfRegister.Text = dr["port_register"].ToString() != "" ? dr["port_register"].ToString() : "N/A";
                    tbPortOfRegister.Text = lblPortOfRegister.Text;


                    DateTime date_var;
                    lblVesselBuiltDate.Text = "N/A";
                    if (DateTime.TryParse(dr["vessel_build_date"].ToString(), out date_var))
                    {
                        tbVesselBuiltDate.Text = date_var.ToShortDateString();
                        lblVesselBuiltDate.Text = date_var.ToShortDateString();
                    }

                    lblClass.Text = dr["class"].ToString() != "" ? dr["class"].ToString() : "N/A";
                    tbClass.Text = lblClass.Text;  
                    
                    long flag_country_id;
                    lblFlag.Text = "N/A";
                    if (long.TryParse(dr["flag_country_id"].ToString(), out flag_country_id))
                    {
                        lblFlag.Text = LoadCountryById(flag_country_id, false);
                        if (ddlFlag.Items.FindByValue(dr["flag_country_id"].ToString()) != null)
                        {
                            ddlFlag.Items.FindByValue(dr["flag_country_id"].ToString()).Selected = true;
                        }
                    }

                    lblClass.Text = dr["class"].ToString() != "" ? dr["class"].ToString() : "N/A";
                    tbClass.Text = lblClass.Text;  

                    lblTimeOfDuration.Text = dr["time_duration"].ToString() != "" ? dr["time_duration"].ToString() : "N/A";
                    tbTimeOfDuration.Text = lblTimeOfDuration.Text;


                    lblPrice.Text = dr["price"].ToString() != "" ? dr["price"].ToString() : "N/A";
                    tbPrice.Text = lblPrice.Text;

                    long special_conditions_id;
                    lblSpecualConditionTypes.Text = "N/A";
                    if (long.TryParse(dr["special_conditions_id"].ToString(), out special_conditions_id))
                    {
                        lblSpecualConditionTypes.Text = LoadUniversalType(special_conditions_id);
                        if (ddlSpecualConditionTypes.Items.FindByValue(dr["special_conditions_id"].ToString()) != null)
                        {
                            ddlSpecualConditionTypes.Items.FindByValue(dr["special_conditions_id"].ToString()).Selected = true;
                        }
                    }

                    string _routes =  "N/A";
                    if (dr["route"] != null)
                    {
                        string[] routes = dr["route"].ToString().Split(',');

                        if (routes.Length > 0) _routes = "";
                        for (int i = 0; i < routes.Length; i++)
                        {
                            long route_id = 0;
                            if (Int64.TryParse(routes[i], out route_id))
                            {
                                _routes += LoadUniversalType(route_id) + "<br/>";
                                ddlRute.SelectedValue = route_id.ToString();
                            }
                        }
                        foreach (ListItem l in ddlRute.Items)
                        {
                            if (routes.Contains(l.Value))
                            {
                                l.Attributes.Add("selected", "selected");
                            }
                        }
                    }
                   
                    lblRute.Text = (_routes!="")?_routes:"N/A";

                    lblOtherInfo.Text = dr["other_information"].ToString() != "" ? dr["other_information"].ToString() : "N/A";
                    tbOtherInformattions.Text = lblOtherInfo.Text;
                }
            }
        }
    }

    #region LoadUniversalType
    private string LoadUniversalType(long id)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            string cmd1 = "";
            Int64 langId = DAO.Connection.DEFAULT_LANGUAGE;
            if (Session["language"] != null)
            {
                Int64.TryParse(Session["language"].ToString(), out langId);
            }
            if (langId != DAO.Connection.DEFAULT_LANGUAGE)
                cmd1 = "SELECT id, name FROM dbo.Fn_GetUniversalTypeByLang(@id,@language_id)";
            else
                cmd1 = "SELECT id, name FROM dbo.Fn_GetUniversalTypeById(@id,@language_id)";
            using (SqlCommand cmd = new SqlCommand(cmd1, conn))
            {
                cmd.Parameters.Add("id", id);
                cmd.Parameters.Add("language_id", langId);

                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    return dr["name"].ToString();
                }
                dr.Close();
                return "";
            }
        }
    }
    #endregion

    #region LoadCountryById
    private string LoadCountryById(long id, bool short_name)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT id, short, name FROM dbo.Fn_GetPlace(@id)", conn))
            {
                cmd.Parameters.Add("id", id);
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    if (short_name)
                        return dr["short"].ToString();
                    else
                        return dr["name"].ToString();
                }
                dr.Close();
                return "";
            }
        }
    }
    #endregion

    private void LoadRoutes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,1000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 21);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlRute.Items.Clear();
                //ddlRute.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlRute.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void setAttributes()
    {
        //ddlSeaPortLoading.Attributes.Add("validate", "true");
        ddlFlag.Attributes.Add("validate", "true");
        ddlVeselTypes.Attributes.Add("validate", "true");
        tbVesselBuiltDate.Attributes.Add("validate", "true");
        ddlRute.Attributes.Add("multiple", "multiple");
        //ddlLevelOfImportnce.Attributes.Add("validate", "true");
        ddlPlacementTypes.Attributes.Add("validate", "true");
    }

    private void LoadDeparture()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT id, short, name FROM dbo.Fn_GetAllPlaces(0, 1000000, 'id', 'asc', 2) WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                ddlDeparture.Items.Clear();
                ddlFlag.Items.Clear();
                ddlDeparture.Items.Add(new ListItem("", "0"));
                ddlFlag.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlDeparture.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    ddlFlag.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadSeaPort()
    {
        
    }

    private void LoadVesselTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,1000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 3);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlVeselTypes.Items.Clear();
                ddlVeselTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlVeselTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadSpecialCondTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,1000,'id','desc') WHERE isActive = 'true'", conn))
            {

                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 5);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlSpecualConditionTypes.Items.Clear();
                ddlSpecualConditionTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlSpecualConditionTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadLevelOfImportanceTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,1000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 16);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlLevelOfImportnce.Items.Clear();
                ddlLevelOfImportnce.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlLevelOfImportnce.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadPlacementTypes(Int64 langId)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * from dbo.Fn_GetTypeByType(@language_id,@type_id,0,1000,'id','desc') WHERE isActive = 'true'", conn))
            {
                SqlParameter[] pars = new SqlParameter[2];
                pars[0] = new SqlParameter("language_id", langId);
                pars[1] = new SqlParameter("type_id", 8);

                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                SqlDataReader dr = cmd.ExecuteReader();
                ddlPlacementTypes.Items.Clear();
                ddlPlacementTypes.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlPlacementTypes.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

}
